package tools

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"fmt"
)

//2Kda0DKs
var DesKey = []byte("2Kda0DKs")
var DesKeyP = []byte("3TM87vyQ")

func GetDesIV() []byte {
	return bytes.ToUpper(DesKey)
}

func GetDesIVP() []byte {
	return bytes.ToUpper(DesKeyP)
}

//DES加密
func DesEncrypt(origData, key, iv []byte) (string, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, iv)
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	//crypted := origData
	blockMode.CryptBlocks(crypted, origData)
	//base64加密
	encodeString := base64.StdEncoding.EncodeToString(crypted)
	return encodeString, nil
}

//DES加密
func DesWithHexEncrypt(origData, key, iv []byte) (string, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	// origData = ZeroPadding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, iv)
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	//crypted := origData
	blockMode.CryptBlocks(crypted, origData)
	//[]byte to 16进制
	return hex.EncodeToString(crypted), nil
}
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

//DES解密
func DesDecrypt(encodeString string, key, iv []byte) (string, error) {
	//base64解密
	crypted, err := base64.StdEncoding.DecodeString(encodeString)
	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	blockMode := cipher.NewCBCDecrypter(block, iv)
	origData := crypted
	blockMode.CryptBlocks(origData, crypted)
	//origData = PKCS5UnPadding(origData)

	origData = ZeroUnPadding(origData)
	return string(origData), nil
}

//DES解密
func DesWithHexDecrypt(encodeString string, key, iv []byte) (string, error) {
	//16进制 to []byte
	crypted, err := hex.DecodeString(encodeString)
	if err != nil {
		return "", err
	}
	block, err := des.NewCipher(key)
	if err != nil {
		return "", err
	}
	blockMode := cipher.NewCBCDecrypter(block, iv)
	origData := crypted
	blockMode.CryptBlocks(origData, crypted)
	//origData = PKCS5UnPadding(origData)
	origData = ZeroUnPadding(origData)

	if len(origData) == 0 {
		return "", errors.New(fmt.Sprintf("DesWithHexDecrypt Failed %s", encodeString))
	}
	return string(origData), nil
}

func ZeroUnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}
